<?php

class Admin extends CI_Controller {
	
	/**
	 * Check if the user is logged in, if he's not, 
	 * send him to the login page
	 * @return void
	 */
	function index() {
		if ($this->session->userdata('admin')) {
			redirect('admin/dashboard');
		} else {
			$this->load->view('admin/login');
		}
	}
	
	/**
	 * encript the password 
	 * @return mixed
	 */
	function __encrip_password($password) {
		return md5($password);
	}
	
	/**
	 * check the username and the password with the database
	 * @return void
	 */
	function validate() {		
		$this->load->model('Users_m', 'user');		
		$username = $this->input->post('username');
		$password  = $this->__encrip_password($this->input->post('password'));		
		$row = $this->user->validate($username, $password);		
		if ($row) {
			$data = array(
				'id'				=>	$row[0]->id,
				'username'		=> $username,
				'ho_ten'			=> $row[0]->ho_ten,
				'role'			=>	$row[0]->role
			);
			$this->session->set_userdata('admin', $data);
			redirect(base_url('admin/dashboard'));
		}else{
			$data['message_error'] = TRUE;
			$this->load->view('admin/login', $data);
		}
	}
	
	/**
	 * Destroy the session, and logout the user.
	 * @return void
	 */
	function logout() {
		$this->session->unset_userdata('admin');
		redirect(base_url('admin'));
	}
	
}